page.tsx 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382
  1. 'use client';
  2. import { use, useCallback, useEffect, useState } from 'react';
  3. import Link from 'next/link';
  4. import { useRouter } from 'next/navigation';
  5. import { fetchApi, getDateTime } from '@/lib/utils/client';
  6. import Loading from '@/app/component/Loading';
  7. import NavTabs from '../../navTabs';
  8. import {
  9. ORDER_STATUS_LABEL,
  10. SHIPMENT_STATUS_LABEL,
  11. REFUND_REASON_LABEL,
  12. REFUND_TYPE_LABEL,
  13. REFUND_STATUS_LABEL,
  14. type OrderDetail,
  15. type RefundReasonType,
  16. type RefundType
  17. } from '@/types/store';
  18. const REASON_OPTIONS: { value: RefundReasonType; label: string }[] = [
  19. { value: 1, label: REFUND_REASON_LABEL[1] },
  20. { value: 2, label: REFUND_REASON_LABEL[2] },
  21. { value: 3, label: REFUND_REASON_LABEL[3] },
  22. { value: 4, label: REFUND_REASON_LABEL[4] },
  23. { value: 5, label: REFUND_REASON_LABEL[5] },
  24. { value: 6, label: REFUND_REASON_LABEL[6] },
  25. { value: 7, label: REFUND_REASON_LABEL[7] }
  26. ];
  27. export default function OrderDetailPage({ params }: { params: Promise<{ id: string }> })
  28. {
  29. const { id } = use(params);
  30. const orderID = parseInt(id, 10);
  31. const router = useRouter();
  32. const [order, setOrder] = useState<OrderDetail|null>(null);
  33. const [loading, setLoading] = useState(true);
  34. const [error, setError] = useState<string|null>(null);
  35. const [refundOpen, setRefundOpen] = useState<RefundType|null>(null);
  36. const [reasonType, setReasonType] = useState<RefundReasonType>(1);
  37. const [reasonMemo, setReasonMemo] = useState('');
  38. const [submitting, setSubmitting] = useState(false);
  39. const load = useCallback(async () => {
  40. setLoading(true);
  41. const res = await fetchApi<OrderDetail>(`/api/store/orders/${orderID}`, { silent: true });
  42. if (res.success && res.data) {
  43. setOrder(res.data);
  44. setError(null);
  45. }
  46. else {
  47. setError(res.message || '주문을 불러올 수 없습니다.');
  48. }
  49. setLoading(false);
  50. }, [orderID]);
  51. useEffect(() => {
  52. load();
  53. }, [load]);
  54. const openModal = (type: RefundType) => {
  55. setRefundOpen(type);
  56. setReasonType(type === 3 ? 2 : 1);
  57. setReasonMemo('');
  58. };
  59. const closeModal = () => {
  60. setRefundOpen(null);
  61. setReasonMemo('');
  62. };
  63. const handleSubmit = async () => {
  64. if (refundOpen === null) {
  65. return;
  66. }
  67. if (reasonType === 7 && !reasonMemo.trim()) {
  68. alert('사유가 "기타"인 경우 상세 사유를 입력해 주세요.');
  69. return;
  70. }
  71. setSubmitting(true);
  72. const res = await fetchApi(`/api/store/orders/${orderID}/refunds`, {
  73. method: 'POST',
  74. body: {
  75. type: refundOpen,
  76. reasonType,
  77. reasonMemo: reasonMemo.trim() || null
  78. },
  79. silent: true
  80. });
  81. setSubmitting(false);
  82. if (res.success) {
  83. alert('환불 요청이 접수되었습니다. 관리자 검토 후 처리됩니다.');
  84. closeModal();
  85. load();
  86. }
  87. else {
  88. alert(res.message || '환불 요청에 실패했습니다.');
  89. }
  90. };
  91. if (loading) {
  92. return (
  93. <>
  94. <NavTabs />
  95. <Loading />
  96. </>
  97. );
  98. }
  99. if (error || !order) {
  100. return (
  101. <>
  102. <NavTabs />
  103. <div className="container mx-auto px-4 py-12 text-center">
  104. <p className="text-red-600 mb-4">{error || '주문을 찾을 수 없습니다.'}</p>
  105. <Link href="/orders" className="text-blue-600 underline">주문 내역으로</Link>
  106. </div>
  107. </>
  108. );
  109. }
  110. const canCancel = order.status === 2 || order.status === 3;
  111. const canReturnExchange = order.status === 5;
  112. const hasPending = order.refunds.some(r => r.status === 1);
  113. const subtotal = order.items.reduce((acc, it) => acc + it.unitPrice * it.quantity, 0);
  114. const shippingFee = order.shipment?.shippingFee ?? 0;
  115. return (
  116. <>
  117. <NavTabs />
  118. <div className="container mx-auto px-4 py-6 max-w-2xl">
  119. <div className="mb-4 flex items-center justify-between">
  120. <button type="button" onClick={() => router.push('/orders')} className="text-sm text-blue-600 hover:underline">
  121. ← 주문 내역
  122. </button>
  123. <button type="button" onClick={() => window.print()} className="text-xs text-neutral-500 hover:text-neutral-700">
  124. 인쇄
  125. </button>
  126. </div>
  127. {/* 영수증 카드 */}
  128. <div className="bg-white dark:bg-neutral-900 border border-neutral-300 dark:border-neutral-700 rounded-lg p-6 shadow-sm">
  129. {/* 헤더 */}
  130. <div className="text-center border-b border-dashed border-neutral-300 dark:border-neutral-700 pb-4 mb-4">
  131. <div className="text-xs tracking-widest text-neutral-500 uppercase">Order Receipt</div>
  132. <div className="font-mono text-lg font-bold mt-1">{order.orderNumber}</div>
  133. <div className="text-xs text-neutral-500 mt-1">{getDateTime(order.createdAt)}</div>
  134. <div className="mt-2">
  135. <span className="inline-block px-3 py-1 rounded-full text-xs font-semibold bg-blue-100 text-blue-800 dark:bg-blue-900/40 dark:text-blue-300">
  136. {ORDER_STATUS_LABEL[order.status]}
  137. </span>
  138. </div>
  139. </div>
  140. {/* 주문자/채널 메타 */}
  141. <dl className="text-xs space-y-1 mb-4">
  142. {order.paidAt && (
  143. <div className="flex justify-between"><dt className="text-neutral-500">결제 일시</dt><dd>{getDateTime(order.paidAt)}</dd></div>
  144. )}
  145. {order.channelName && (
  146. <div className="flex justify-between"><dt className="text-neutral-500">후원 채널</dt><dd>{order.channelName}</dd></div>
  147. )}
  148. </dl>
  149. {/* 아이템 */}
  150. <div className="border-t border-neutral-200 dark:border-neutral-800 pt-3">
  151. <table className="w-full text-sm">
  152. <thead>
  153. <tr className="text-xs text-neutral-500 border-b border-neutral-200 dark:border-neutral-800">
  154. <th className="text-left py-1 font-normal">상품</th>
  155. <th className="text-right py-1 font-normal w-12">수량</th>
  156. <th className="text-right py-1 font-normal w-24">소계</th>
  157. </tr>
  158. </thead>
  159. <tbody>
  160. {order.items.map((item) => (
  161. <tr key={item.id} className="border-b border-neutral-100 dark:border-neutral-800/60 last:border-0">
  162. <td className="py-2 align-top">
  163. <div className="flex items-start gap-2">
  164. <div className="w-10 h-10 bg-neutral-100 dark:bg-neutral-800 rounded overflow-hidden flex-shrink-0">
  165. {item.productThumbnail ? (
  166. // eslint-disable-next-line @next/next/no-img-element
  167. <img src={item.productThumbnail} alt="" className="w-full h-full object-cover" />
  168. ) : null}
  169. </div>
  170. <div className="min-w-0">
  171. <div className="font-medium truncate">{item.productName}</div>
  172. <div className="text-xs text-neutral-500">
  173. {item.type === 1 ? '실물' : '쿠폰'} · {item.unitPrice.toLocaleString()}P
  174. </div>
  175. {item.type === 2 && item.issuedCouponCodeID !== null && (
  176. <Link href="/inventory" className="text-xs text-blue-600 hover:underline">보관함에서 확인 →</Link>
  177. )}
  178. </div>
  179. </div>
  180. </td>
  181. <td className="py-2 text-right align-top tabular-nums">{item.quantity}</td>
  182. <td className="py-2 text-right align-top tabular-nums">{(item.unitPrice * item.quantity).toLocaleString()}P</td>
  183. </tr>
  184. ))}
  185. </tbody>
  186. </table>
  187. </div>
  188. {/* 합계 */}
  189. <div className="border-t border-neutral-200 dark:border-neutral-800 mt-3 pt-3 text-sm space-y-1">
  190. <div className="flex justify-between text-neutral-600 dark:text-neutral-400">
  191. <span>상품 금액</span>
  192. <span className="tabular-nums">{subtotal.toLocaleString()}P</span>
  193. </div>
  194. {shippingFee > 0 && (
  195. <div className="flex justify-between text-neutral-600 dark:text-neutral-400">
  196. <span>배송비</span>
  197. <span className="tabular-nums">{shippingFee.toLocaleString()}P</span>
  198. </div>
  199. )}
  200. <div className="flex justify-between items-baseline pt-2 mt-1 border-t border-dashed border-neutral-300 dark:border-neutral-700">
  201. <span className="text-base font-bold">총 결제 금액</span>
  202. <span className="text-xl font-extrabold text-red-600 dark:text-red-400 tabular-nums">{order.totalAmount.toLocaleString()}P</span>
  203. </div>
  204. </div>
  205. {/* 배송 정보 */}
  206. {order.shipment && (
  207. <div className="border-t border-neutral-200 dark:border-neutral-800 mt-4 pt-3 text-xs space-y-1">
  208. <div className="font-semibold mb-1">배송 정보</div>
  209. <div className="flex justify-between"><span className="text-neutral-500">상태</span><span>{SHIPMENT_STATUS_LABEL[order.shipment.status]}</span></div>
  210. <div className="flex justify-between"><span className="text-neutral-500">택배사</span><span>{order.shipment.carrier || '-'}</span></div>
  211. <div className="flex justify-between"><span className="text-neutral-500">송장번호</span><span className="font-mono">{order.shipment.trackingNumber || '-'}</span></div>
  212. {order.shipment.shippedAt && (
  213. <div className="flex justify-between"><span className="text-neutral-500">출고</span><span>{getDateTime(order.shipment.shippedAt)}</span></div>
  214. )}
  215. {order.shipment.deliveredAt && (
  216. <div className="flex justify-between"><span className="text-neutral-500">배송 완료</span><span>{getDateTime(order.shipment.deliveredAt)}</span></div>
  217. )}
  218. </div>
  219. )}
  220. {/* 환불 요청 이력 */}
  221. {order.refunds.length > 0 && (
  222. <div className="border-t border-neutral-200 dark:border-neutral-800 mt-4 pt-3 text-xs space-y-2">
  223. <div className="font-semibold">환불 요청 이력</div>
  224. {order.refunds.map((r) => (
  225. <div key={r.id} className="border border-neutral-200 dark:border-neutral-800 rounded p-2">
  226. <div className="flex justify-between items-center mb-1">
  227. <span className="font-semibold">{REFUND_TYPE_LABEL[r.type]} · {REFUND_REASON_LABEL[r.reasonType]}</span>
  228. <span className="px-1.5 py-0.5 rounded text-[10px] font-semibold bg-neutral-100 text-neutral-700 dark:bg-neutral-800 dark:text-neutral-300">
  229. {REFUND_STATUS_LABEL[r.status]}
  230. </span>
  231. </div>
  232. {r.reason && r.reason !== REFUND_REASON_LABEL[r.reasonType] && (
  233. <div className="text-neutral-600 dark:text-neutral-400 break-words">사유: {r.reason}</div>
  234. )}
  235. {r.adminMemo && (
  236. <div className="text-neutral-500 mt-1">관리자: {r.adminMemo}</div>
  237. )}
  238. <div className="text-neutral-400 mt-1">요청 {getDateTime(r.requestedAt)}{r.resolvedAt && ` · 처리 ${getDateTime(r.resolvedAt)}`}</div>
  239. </div>
  240. ))}
  241. </div>
  242. )}
  243. {/* 영수증 푸터 */}
  244. <div className="text-center text-xs text-neutral-400 mt-6 border-t border-dashed border-neutral-300 dark:border-neutral-700 pt-3">
  245. 이용해 주셔서 감사합니다.
  246. </div>
  247. </div>
  248. {/* 액션 버튼 */}
  249. {!hasPending && (canCancel || canReturnExchange) && (
  250. <div className="mt-4 flex flex-wrap gap-2 justify-center">
  251. {canCancel && (
  252. <button
  253. type="button"
  254. onClick={() => openModal(1)}
  255. className="px-4 py-2 rounded border border-neutral-300 dark:border-neutral-700 text-sm hover:bg-neutral-50 dark:hover:bg-neutral-800"
  256. >
  257. 주문 취소
  258. </button>
  259. )}
  260. {canReturnExchange && (
  261. <>
  262. <button
  263. type="button"
  264. onClick={() => openModal(2)}
  265. className="px-4 py-2 rounded border border-neutral-300 dark:border-neutral-700 text-sm hover:bg-neutral-50 dark:hover:bg-neutral-800"
  266. >
  267. 반품 신청
  268. </button>
  269. <button
  270. type="button"
  271. onClick={() => openModal(3)}
  272. className="px-4 py-2 rounded border border-neutral-300 dark:border-neutral-700 text-sm hover:bg-neutral-50 dark:hover:bg-neutral-800"
  273. >
  274. 교환 신청
  275. </button>
  276. </>
  277. )}
  278. </div>
  279. )}
  280. {hasPending && (
  281. <div className="mt-4 text-center text-xs text-amber-600">
  282. 이미 처리 대기 중인 환불 요청이 있습니다. 관리자 검토 후 다시 신청하실 수 있습니다.
  283. </div>
  284. )}
  285. </div>
  286. {/* 환불 요청 모달 */}
  287. {refundOpen !== null && (
  288. <div className="fixed inset-0 bg-black/50 z-50 flex items-center justify-center p-4" onClick={closeModal}>
  289. <div
  290. className="bg-white dark:bg-neutral-900 rounded-lg w-full max-w-md p-5"
  291. onClick={(e) => e.stopPropagation()}
  292. >
  293. <h2 className="text-lg font-bold mb-3">
  294. {REFUND_TYPE_LABEL[refundOpen]} 신청
  295. </h2>
  296. <p className="text-xs text-neutral-500 mb-4">
  297. {refundOpen === 1
  298. ? '주문 취소를 신청합니다. 관리자 검토 후 처리되며, 결제 금액은 사용한 잔액 유형으로 환원됩니다.'
  299. : '신청 후 관리자 검토를 거쳐 처리됩니다. 배송 완료 후 30일 이내만 신청할 수 있습니다.'}
  300. </p>
  301. <label className="block text-xs font-semibold mb-1">사유 유형</label>
  302. <select
  303. value={reasonType}
  304. onChange={(e) => setReasonType(Number(e.target.value) as RefundReasonType)}
  305. className="w-full border border-neutral-300 dark:border-neutral-700 rounded px-3 py-2 text-sm mb-3 bg-white dark:bg-neutral-900"
  306. >
  307. {REASON_OPTIONS.map((opt) => (
  308. <option key={opt.value} value={opt.value}>{opt.label}</option>
  309. ))}
  310. </select>
  311. <label className="block text-xs font-semibold mb-1">
  312. 상세 사유 {reasonType === 7 && <span className="text-red-600">*</span>}
  313. </label>
  314. <textarea
  315. value={reasonMemo}
  316. onChange={(e) => setReasonMemo(e.target.value)}
  317. maxLength={500}
  318. rows={4}
  319. placeholder={reasonType === 7 ? '기타 사유를 입력해 주세요' : '추가 설명이 있다면 입력해 주세요 (선택)'}
  320. className="w-full border border-neutral-300 dark:border-neutral-700 rounded px-3 py-2 text-sm bg-white dark:bg-neutral-900 resize-none"
  321. />
  322. <div className="text-[10px] text-neutral-400 text-right mt-0.5">{reasonMemo.length}/500</div>
  323. <div className="flex gap-2 mt-4 justify-end">
  324. <button
  325. type="button"
  326. onClick={closeModal}
  327. disabled={submitting}
  328. className="px-4 py-2 rounded border border-neutral-300 dark:border-neutral-700 text-sm hover:bg-neutral-50 dark:hover:bg-neutral-800"
  329. >
  330. 취소
  331. </button>
  332. <button
  333. type="button"
  334. onClick={handleSubmit}
  335. disabled={submitting}
  336. className="px-4 py-2 rounded bg-blue-600 text-white text-sm hover:bg-blue-700 disabled:opacity-50"
  337. >
  338. {submitting ? '신청 중...' : '신청하기'}
  339. </button>
  340. </div>
  341. </div>
  342. </div>
  343. )}
  344. </>
  345. );
  346. }